package com.dashu.device.tools.System;

import com.dashu.base.bean.device.System.CpuBean;
import com.dashu.base.bean.device.System.CpuCore;
import org.hyperic.sigar.CpuInfo;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;

import java.util.ArrayList;
import java.util.List;

public class Cpu {

    /**
     * 获取cpu的信息
     * @return
     * @throws SigarException
     */
    public static CpuBean cpu(){
        Sigar sigar = new Sigar();
        CpuInfo infos[];

        CpuBean cpuBean = new CpuBean();
        try {
            infos = sigar.getCpuInfoList();
            CpuPerc cpuList[];
            cpuList = sigar.getCpuPercList();

            List<CpuCore> list = new ArrayList<>();
            for (int i = 0; i < infos.length; i++) {// 不管是单块CPU还是多CPU都适用
                CpuCore cpuCore = new CpuCore();
                CpuInfo info = infos[i];
                cpuCore.setCoreCpu((i + 1));
                cpuBean.setMhzCpu(info.getMhz());
                cpuBean.setModelCpu(info.getModel());
                cpuBean.setVendorCpu(info.getVendor());
                cpuBean.setCacheCpu(info.getCacheSize());
                cpuCore.setCombinedCpu(cpuList[i].getCombined());
                cpuCore.setIdleCpu(cpuList[i].getIdle());
                cpuCore.setNiceCpu(cpuList[i].getNice());
                cpuCore.setSysCpu(cpuList[i].getCombined());
                cpuCore.setUseCpu(cpuList[i].getUser());
                cpuCore.setWaitCpu(cpuList[i].getWait());
                cpuCore.setSysCpu(cpuList[i].getSys());
                list.add(cpuCore);
                cpuBean.setCpuCores(list);

            }
        } catch (SigarException e) {
            e.printStackTrace();
        }

        return cpuBean;
    }



//            System.out.println("第" + (i + 1) + "块CPU信息");
//            System.out.println("CPU的总量MHz:  " + info.getMhz());// CPU的总量MHz
//            System.out.println("CPU生产商:  " + info.getVendor());// 获得CPU的卖主，如：Intel
//            System.out.println("CPU类别:  " + info.getModel());// 获得CPU的类别，如：Celeron
//            System.out.println("CPU缓存数量:  " + info.getCacheSize());// 缓冲存储器数量
//            printCpuPerc(cpuList[i]);

    private static void printCpuPerc(CpuPerc cpu) {
        System.out.println("CPU用户使用率:  " + CpuPerc.format(cpu.getUser()));// 用户使用率
        System.out.println("CPU系统使用率:  " + CpuPerc.format(cpu.getSys()));// 系统使用率
        System.out.println("CPU当前等待率:  " + CpuPerc.format(cpu.getWait()));// 当前等待率
        System.out.println("CPU当前错误率:  " + CpuPerc.format(cpu.getNice()));//
        System.out.println("CPU当前空闲率:  " + CpuPerc.format(cpu.getIdle()));// 当前空闲率
        System.out.println("CPU总的使用率:  " + CpuPerc.format(cpu.getCombined()));// 总的使用率
    }


}
